package entity

import (
	"fmt"
	"strconv"
	"strings"

	"gorm.io/gorm"
	"shqsoft.cn/pas3ui/base"
)

// CompJgh 公司机构户
type CompJgh struct {
	ID     int    `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	NY     int    `gorm:"column:NY"`
	CUID   int    `gorm:"column:CUID"`
	KHMC   string `gorm:"column:KHMC"`
	ISCZH  string `gorm:"column:ISCZH"`
	ISJGTT string `gorm:"column:ISJGTT"`
	KJ     string `gorm:"column:KJ"`
	DRJG   string `gorm:"column:DRJG"`
	DTID   int    `gorm:"column:DTID"`
}

// TableName 公司机构户导入表
func (CompJgh) TableName() string {
	return "T_COMP_JGH"
}

// BeforeCreate
func (i *CompJgh) BeforeCreate(tx *gorm.DB) (err error) {
	err = base.CHDB.Raw("select CUID from T_COMP_CLIE where CUNM=?", i.KHMC).Row().Scan(&i.CUID)
	if err != nil {
		err = fmt.Errorf("客户【%s】在系统中不存在！", i.KHMC)
		return
	}

	if strings.Contains(i.KHMC, "财政") {
		i.ISCZH = "是"
		i.ISJGTT = "否"
	} else {
		i.ISCZH = "否"
		i.ISJGTT = "是"
	}

	dtid := strconv.Itoa(i.NY)
	dtid = dtid[:4] + "-" + dtid[4:6] + "-01"
	err = tx.Raw("SELECT REPLACE (LAST_DAY(STR_TO_DATE(?, '%Y-%m-%d')),'-','')as dtid;", dtid).Row().Scan(&i.DTID)

	return
}

// CompJghEF 返回结构体
func CompJghEF() base.EntityFunc {
	return func() interface{} {
		entity := CompJgh{}
		return &entity
	}
}

// CompJghESF 返回结构体数组
func CompJghESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []CompJgh
		return &entities
	}
}

func init() {
	base.DaoPoolObj.Put("CompJgh", base.NewDefaultDao(CompJghEF(), CompJghESF(), nil, "my"))
}
